<template>
  <div class="compact-container">
    <!-- Compact search row -->
    <div class="search-row">
      <span class="search-label">产品分类名称（编码）：</span>
      <el-input v-model="typeName" class="search-input" size="small" />
      <span class="search-label">状态：</span>
      <el-select v-model="typeStatus" placeholder="状态" class="status-select" size="small">
        <el-option label="查询全部" value="2" />
        <el-option label="正常" value="0" />
        <el-option label="停用" value="1" />
      </el-select>
      <el-button type="primary" size="small" @click="query">查询</el-button>
      <el-button size="small" @click="reset">重置</el-button>
      <div class="flex-grow"></div>
      <el-button type="primary" size="small" @click="addEdit">添加</el-button>
    </div>

    <el-divider style="margin: 6px 0" />

    <!-- Compact table area -->
    <div class="table-wrapper">
      <el-table :data="tableData" style="width: 100%" row-key="pro_type_id" border
        :cell-style="{ textAlign: 'center', padding: '4px 0' }" :header-cell-style="{
          textAlign: 'center',
          background: '#f5f7fa',
          fontWeight: 'bold',
          position: 'sticky',
          top: 0,
          padding: '4px 0',
          height: '36px'
        }" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" default-expand-all>
        <el-table-column prop="pro_type_id" label="序号" />
        <el-table-column prop="pro_type_code" label="产品类型编号" width="180" />
        <el-table-column prop="pro_type_name" label="产品类型名称" />
        <el-table-column prop="pro_type_sort" label="排序" />
        <el-table-column prop="pro_type_status" label="状态">
          <template #default="scope">
            {{ scope.row.pro_type_status == 0 ? "正常" : "停用" }}
          </template>
        </el-table-column>
        <el-table-column prop="create_by" label="提交人" />
        <el-table-column prop="create_time" label="提交时间" width="200">
          <template #default="scope">
            {{ scope.row.create_time.replace('T', ' ') }}
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="180">
          <template #default="scope">
            <div class="action-group">
              <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- Centered pagination -->
      <div class="pagination-center">
        <el-pagination small v-model:current-page="currentPage" v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20, 50]" :background="true" layout="total, sizes, prev, pager, next, jumper"
          :total="pageCount" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </div>

    <!-- Add/Edit Drawers -->
    <el-drawer v-model="dialogVisible" title="添加产品分类信息" :direction="direction" :before-close="handleClose" size="45%"
      @close="close">
      <el-form name="configfilefirstkindForm" method="post" ref="ruleFormRef" :model="pro_type" :rules="rules"
        label-width="80px" class="demo-ruleForm">
        <div style="display: flex; justify-content: space-between;">
          <div style="width: 48%;">
            <el-form-item prop="parent_id" label="上级分类" label-width="106" style="margin-bottom: 30px;">
              <el-tree-select v-model="pro_type.parent_id" :data="options" :props="defaultProps" :check-strictly="true"
                placeholder="请选择上级分类" style="width: 110%;margin-left: -22;" />
            </el-form-item>

            <el-form-item label="产品类型名称" prop="pro_type_name" label-width="106" style="margin-bottom: 30px;">
              <el-input v-model="pro_type.pro_type_name" placeholder="产品类型名称" clearable style="width: 210px; " />
            </el-form-item>
            <el-form-item label="状态" style="display: flex; justify-content: center;margin-bottom: 30px;"
              label-width="106">
              <el-radio-group v-model="pro_type.pro_type_status">
                <el-radio value="0">正常</el-radio>
                <el-radio value="1">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>

          <div style="width: 48%;">
            <el-form-item label="产品类型编号" prop="user_sex" label-width="100" style="margin-bottom: 30px;">
              <el-input v-model="pro_type.pro_type_code" placeholder="自动获取产品类型编号" clearable disabled
                style="width: 240px; " />
            </el-form-item>
            <el-form-item prop="pro_type_sort" label="排序" label-width="100" style="margin-bottom: 30px;">
              <el-input v-model="pro_type.pro_type_sort" placeholder="排序" clearable style="width: 240px; " />
            </el-form-item>
          </div>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="close">取消</el-button>
          <el-button type="primary" @click="pro_type_Edit">
            确定
          </el-button>
        </div>
      </template>
    </el-drawer>

    <el-drawer v-model="dialogVisible1" title="修改产品分类信息" :direction="direction" :before-close="handleClose" size="45%"
      @close="close">
      <el-form name="configfilefirstkindForm" method="post" ref="ruleFormRef" :model="pro_type" :rules="rules"
        label-width="80px" class="demo-ruleForm">
        <div style="display: flex; justify-content: space-between;">
          <div style="width: 48%;">
            <el-form-item prop="parent_id" label="上级分类" label-width="106" style="margin-bottom: 30px;">
              <el-tree-select v-model="pro_type.parent_id" :data="options" :props="defaultProps" :check-strictly="true"
                placeholder="请选择上级分类" />
            </el-form-item>

            <el-form-item label="产品类型名称" prop="pro_type_name" label-width="106" style="margin-bottom: 30px;">
              <el-input v-model="pro_type.pro_type_name" placeholder="产品类型名称" clearable style="width: 210px; " />
            </el-form-item>
            <el-form-item label="状态" style="display: flex; justify-content: center;margin-bottom: 30px;"
              label-width="106">
              <el-radio-group v-model="pro_type.pro_type_status">
                <el-radio value="0">正常</el-radio>
                <el-radio value="1">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>

          <div style="width: 48%;">
            <el-form-item label="产品类型编号" prop="user_sex" label-width="100" style="margin-bottom: 30px;">
              <el-input v-model="pro_type.pro_type_code" placeholder="自动获取产品分类编号" clearable disabled
                style="width: 240px; " />
            </el-form-item>
            <el-form-item prop="pro_type_sort" label="排序" label-width="100" style="margin-bottom: 30px;">
              <el-input v-model="pro_type.pro_type_sort" placeholder="排序" clearable style="width: 240px; " />
            </el-form-item>
          </div>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="close">取消</el-button>
          <el-button type="primary" @click="pro_type_Edit">
            确定
          </el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script>
import { ref, reactive, onMounted, markRaw } from 'vue'
import axios from 'axios'
import dayjs from 'dayjs'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { Delete } from '@element-plus/icons-vue'

export default {
  setup() {
    const tableData = ref([])
    const currentPage = ref(1)
    const pageSize = ref(10)
    const pageCount = ref(0)
    const typeName = ref("")
    const typeStatus = ref('2')
    const dialogVisible = ref(false)
    const ruleFormRef = ref(null)
    const dialogVisible1 = ref(false)
    const pro_type = reactive({
      pro_type_id: "0",
      pro_type_name: "",
      pro_type_code: null,
      pro_type_sort: "",
      parent_id: 0,
      pro_type_status: "0",
    })
    const options = ref([])

    const rules = reactive({
      pro_type_name: [
        { required: true, message: "产品编号名称不能为空", trigger: ["blur","change"] },
      ],
      parent_id: [
        { required: true, message: "上级产品不能为空", trigger: ["blur","change"] },
      ],
      pro_type_sort: [
        { required: true, message: "排序不能为空", trigger: ["blur","change"] },
      ]
    })

    onMounted(() => {
      fill()
      count()
      pro_type_Opt()
    })

    function fill() {
      axios.get("http://localhost:5181/api/Product_Type/GetProduct_Types", {
        params: {
          currentPage: currentPage.value,
          pageSize: pageSize.value,
          typeName: typeName.value,
          status: typeStatus.value
        },
        headers: {
          authorization: `Bearer ${localStorage.getItem('token')}`
        }
      }).then((result) => {
        tableData.value = result.data
      }).catch((err) => {
        console.error(err)
      })
    }

    function count() {
      axios.get("http://localhost:5181/api/Product_Type/Product_TypeCount", {
        params: {
          typeName: typeName.value,
          status: typeStatus.value
        },
        headers: {
          authorization: `Bearer ${localStorage.getItem('token')}`
        }
      }).then((result) => {
        pageCount.value = result.data
      }).catch((err) => {
        console.error(err)
      })
    }

    function pro_type_Opt() {
      axios.get("http://localhost:5181/api/Product_Type/GetProduct_Types", {
        params: {
          currentPage: 0,
          pageSize: 0,
          typeName: "",
          status: '0'
        },
        headers: {
          authorization: `Bearer ${localStorage.getItem('token')}`
        }
      }).then((result) => {
        // options.value = convertToTreeOptions(result.data)
        const treeData = convertToTreeOptions(result.data);
        // 添加“无”作为顶级选项（value=0，label=无）
        options.value = [{ value: 0, label: '无' }, ...treeData];
      }).catch((err) => {
        console.error(err)
      })
    }

    const convertToTreeOptions = (items) => {
      return items.map(item => ({
        value: item.pro_type_id,
        label: item.pro_type_name,
        children: item.children && item.children.length > 0
          ? convertToTreeOptions(item.children)
          : []
      }))
    }

    function handleSizeChange(val) {
      pageSize.value = val
      fill()
    }

    function handleCurrentChange(val) {
      currentPage.value = val
      fill()
    }

    function query() {
      fill()
      count()
    }

    function reset() {
      typeName.value = ""
      typeStatus.value = '2'
      query()
    }

    function addEdit() {
      dialogVisible.value = true
    }

    function pro_type_Edit() {
      ruleFormRef.value.validate((valid) => {
        if (valid) {
          if (pro_type.pro_type_id == "0") {
            obtainCode().then(() => {
              pro_type_Add()
            }).catch((err) => {
              console.error(err)
            })
            // pro_type_Add()
          } else {
            pro_type_update()
          }
        }
      })
    }

    function pro_type_Add() {
      const loadingInstance = ElLoading.service({
        lock: true,
        text: '正在添加中...',
        background: 'rgba(0, 0, 0, 0.7)',
      });
      axios.post("http://localhost:5181/api/Product_Type/Product_TypeAdd", {
        pro_type_name: pro_type.pro_type_name,
        pro_type_code: pro_type.pro_type_code,
        pro_type_sort: pro_type.pro_type_sort,
        parent_id: pro_type.parent_id,
        pro_type_status: pro_type.pro_type_status,
        del_flag: '0',
        create_by: localStorage.getItem('userLName'),
        create_time: dayjs().format('YYYY-MM-DDTHH:mm:ss.SSSZ')
      }, {
        headers: {
          authorization: `Bearer ${localStorage.getItem('token')}`
        }
      }).then((result) => {
        if (result.data > 0) {
          ElMessage.success('产品分类信息添加成功！')
          fill()
          count()
          pro_type_Opt()
          close()
        }
      }).catch((err) => {
        console.error(err)
      }).finally(() => {
        loadingInstance.close();
      })
    }

    function pro_type_update() {
      const loadingInstance = ElLoading.service({
        lock: true,
        text: '正在修改中...',
        background: 'rgba(0, 0, 0, 0.7)',
      });
      axios.put("http://localhost:5181/api/Product_Type/Product_TypeUpdate", {
        pro_type_id: pro_type.pro_type_id,
        pro_type_name: pro_type.pro_type_name,
        pro_type_code: pro_type.pro_type_code,
        pro_type_sort: pro_type.pro_type_sort,
        parent_id: pro_type.parent_id,
        pro_type_status: pro_type.pro_type_status,
        update_by: localStorage.getItem('userLName'),
        update_time: dayjs().format('YYYY-MM-DDTHH:mm:ss.SSSZ')
      }, {
        headers: {
          authorization: `Bearer ${localStorage.getItem('token')}`
        }
      }).then((result) => {
        if (result.data > 0) {
          ElMessage.warning('产品分类信息修改成功！')
          fill()
          count()
          pro_type_Opt()
          close()
        }
      }).catch((err) => {
        console.error(err)
      }).finally(() => {
        loadingInstance.close();
      })
    }

    function obtainCode() {
      return axios.get("http://localhost:5181/api/DJBH/DJBH", {
        params: {
          en_code: 1
        }
      }).then((result) => {
        pro_type.pro_type_code = result.data
      }).catch((err) => {
        console.error(err)
      })
    }

    function close() {
      dialogVisible.value = false
      dialogVisible1.value = false
      for (const key in pro_type) {
        pro_type[key] = ""
      }
      pro_type.pro_type_id = "0"
      pro_type.pro_type_status = "0"
      pro_type.parent_id = 0;
    }

    function handleEdit(row) {
      Object.assign(pro_type, row)
      dialogVisible1.value = true
    }

    function getAllChildIds(node) {
      let ids = [];
      // 检查当前节点是否有子节点
      if (node.children && node.children.length > 0) {
        node.children.forEach(child => {
          // 添加子节点的ID
          // ids.push(child.pro_type_id);
          ids.push({
            pro_type_id: child.pro_type_id,
            del_flag: '1'
          });

          // 递归遍历子节点的子节点（孙级）
          ids = ids.concat(getAllChildIds(child));
        });
      }
      return ids;
    }

    function handleDelete(row) {
      ElMessageBox.confirm(
        '此操作将删除'+row.pro_type_name+'产品类型及其子级类型，是否继续？',
        '警告',
        {
          type: 'warning',
          icon: markRaw(Delete),
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }
      )
        .then(() => {
          const product_TypeDelDto = getAllChildIds(row)
          product_TypeDelDto.push({
            pro_type_id: row.pro_type_id,
            del_flag: '1'
          });
          console.info(product_TypeDelDto)
          const loadingInstance = ElLoading.service({
            lock: true,
            text: '正在删除中...',
            background: 'rgba(0, 0, 0, 0.7)',
          });
          axios.put("http://localhost:5181/api/Product_Type/Product_TypeDelete",product_TypeDelDto , {
            headers: {
              'Content-Type': 'application/json',
              authorization: `Bearer ${localStorage.getItem('token')}`
            }
          }).then((result) => {
            if (result.data > 0) {
              ElMessage.success('删除成功！')
              fill()
              count()
            }
          }).catch((err) => {
            console.error(err)
          }).finally(() => {
            loadingInstance.close();
          })
        })
        .catch(() => {
          ElMessage.info('已取消删除')
        })
    }

    return {
      tableData, currentPage, pageSize, pageCount, typeName, typeStatus,
      dialogVisible, ruleFormRef, dialogVisible1, pro_type, options, rules,
      fill, count, handleSizeChange, handleCurrentChange, query, reset,
      addEdit, pro_type_Edit, close, handleEdit, handleDelete
    }
  }
}
</script>

<style scoped>
.compact-container {
  padding: 10px;
}

.search-row {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-bottom: 6px;
  margin-top: -40px;
}

.search-label {
  white-space: nowrap;
  font-size: 13px;
}

.search-input {
  width: 160px !important;
}

.status-select {
  width: 160px !important;
  margin-right: 6px;
}

.flex-grow {
  flex-grow: 1;
}

.table-wrapper {
  margin-top: 6px;
}

.pagination-center {
  display: flex;
  justify-content: center;
  margin-top: 10px;
}

.action-group {
  display: flex;
  justify-content: center;
  gap: 4px;
}

.compact-form {
  padding: 10px;
}

.form-columns {
  display: flex;
  justify-content: space-between;
  gap: 10px;
}

.form-column {
  flex: 1;
}

.form-input {
  width: 100% !important;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  padding: 10px;
  gap: 10px;
}

:deep(.el-table__row) {
  height: 36px !important;
}

:deep(.el-table th.el-table__cell) {
  height: 36px !important;
}

:deep(.el-button--small) {
  padding: 5px 8px;
  height: 24px;
}
</style>